const db = require('../db/index')
const jwt = require('jsonwebtoken')
const config = require('../config')

// 登录处理函数
exports.login=(req,res)=>{
  const value = req.body
  const userSql = 'select * from users where username=?'
  db.query(userSql,value.username,(err,results)=>{
    if(err) return res.send({
      status:1,
      message:err
    })
    if(!results) return res.send({
      status:1,
      message:'获取用户信息失败!'
    })
    if(value.password!==results[0].password || value.username!==results[0].username) return res.send({
      status:1,
      message:'用户名或密码错误!'
    })

    const user = {...results[0],password:''}
   const token = jwt.sign(user,config.jwtSecretKey,{expiresIn:config.expiresIn})
    res.send({
      status:0,
      message:'登录成功!',
      token:'Bearer ' + token
  })
  })
}

